require 'vendor/plugins/railsxmpp/XMPPClient'
require 'vendor/plugins/railsxmpp/config'

class XmppWorker < BackgrounDRb::MetaWorker
  set_worker_name :xmpp_worker
  set_no_auto_load true
  
  def create(args = nil)
    @cl = nil
    @exit = nil
  end
  
  def login p_data
    return if @cl
    thread_pool.defer(p_data) do |p_data|
      begin
        puts "logging in..."
        @cl = XMPPClient.new(CONFIG[:login], CONFIG[:pwd])
        @cl.login
        puts "logged in"
        @tempo = 20
        loop do
          sleep(1)
          #break if tempo <= 0 # without a ping, disconnect
          #@tempo -= 1
          break if @exit
        end
        @cl.close
        rescue Exception => e
        puts "Error, can not log in." + e.Message
      end
      @cl = nil
      exit # exit worker
    end
  end
  
  def set_presence p_data
    puts "set_presence '#{p_data}'"
    return unless @cl
    @cl.set_presence(nil,p_data)
  end
  
  def send_msg p_data
    to, msg = p_data[:to], p_data[:msg]
    puts "#{to}: #{msg}"
    return unless @cl
    @cl.send_msg(to,msg)
  end
  
  def ping
    #@tempo = 30
  end
  
  def log_out
    @exit = true
  end
end
